<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Db;
// 应用公共文件
//有无申请供货商信息并显示数量
//use app\admin\model\SupplierModel;
//function isSupplier(){
//    $SupplierModel=new SupplierModel();
//    $res=$SupplierModel->number();
//    if ($res)
//        echo "<span class='label label-warning pull-right'>".$res."</span>";
//}
////有无申请团长信息并显示数量
//use app\admin\model\CommanderModel;
//function isCommander(){
//    $CommanderModel=new CommanderModel();
//    $res=$CommanderModel->number();
//    if ($res)
//        echo "<span class='label label-warning pull-right'>".$res."</span>";
//}

//修改跳转样式
function isMobile()
{
    if (isset ($_SERVER['HTTP_X_WAP_PROFILE']))
    {
        return true;
    }
    if (isset ($_SERVER['HTTP_VIA']))
    {
        return stristr($_SERVER['HTTP_VIA'], "wap") ? true : false;
    }
    if (isset ($_SERVER['HTTP_USER_AGENT']))
    {
        $clientkeywords = array ('nokia',
            'sony',
            'ericsson',
            'mot',
            'samsung',
            'htc',
            'sgh',
            'lg',
            'sharp',
            'sie-',
            'philips',
            'panasonic',
            'alcatel',
            'lenovo',
            'iphone',
            'ipod',
            'blackberry',
            'meizu',
            'android',
            'netfront',
            'symbian',
            'ucweb',
            'windowsce',
            'palm',
            'operamini',
            'operamobi',
            'openwave',
            'nexusone',
            'cldc',
            'midp',
            'wap',
            'mobile'
        );
        if (preg_match("/(" . implode('|', $clientkeywords) . ")/i", strtolower($_SERVER['HTTP_USER_AGENT'])))
        {
            return true;
        }
    }
    if (isset ($_SERVER['HTTP_ACCEPT']))
    {
        if ((strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') !== false) && (strpos($_SERVER['HTTP_ACCEPT'], 'text/html') === false || (strpos($_SERVER['HTTP_ACCEPT'], 'vnd.wap.wml') < strpos($_SERVER['HTTP_ACCEPT'], 'text/html'))))
        {
            return true;
        }
    }
    return false;
}
//变更金额
//用户id   变更金额类型  加减  变更金额 变更类型
function changeBalance($uid,$balanceType,$sign,$money,$from_type,$remark="",$balance_type)
{
    $blanceInfo=Db::name("balance")->where("uid",$uid)->find();
    if(empty($blanceInfo))
    {
        $addBblance=array(
            "uid"=>$uid,
        );
        $res=Db::name("balance")->insert($addBblance);
        if($res)
        {
            $blanceInfo=Db::name("balance")->where("uid",$uid)->find();
        }
    }
    if($sign==1)
    {
        $before_balance = abs($blanceInfo[$balanceType]);
        $later_balance = abs($blanceInfo[$balanceType]+$money);
        $resUpdateBalance=Db::name("balance")->where("uid",$uid)->setInc($balanceType,$money);
//        if($from_type==1)
//        {
//            Db::name("user_money")->where("user_id",$uid)->setInc("earnings",$money);
//        }elseif($from_type==2)
//        {
//            Db::name("user_money")->where("user_id",$uid)->setInc("recom_money",$money);
//        }elseif($from_type==5)
//        {
//            Db::name("user_money")->where("user_id",$uid)->setInc("team_money",$money);
//        }
    }else if($sign==0)
    {
        if($blanceInfo[$balanceType]-$money<0)
        {
            return false;
        }
        $before_balance = abs($blanceInfo[$balanceType]);
        $later_balance = abs($blanceInfo[$balanceType]-$money);
        $resUpdateBalance=Db::name("balance")->where("uid",$uid)->setDec($balanceType,$money);
    }
    $arrInsertLog=array(
        "uid"=>$uid,
        "sign"=>$sign,
        "balance"=>$money,
        "balance_type"=>$balance_type,
        "type"=>$from_type,
        "createtime"=>time(),
        "message"=>$remark,
        "before_balance"=>$before_balance,
        "later_balance"=>$later_balance,
    );
    $resInsert=Db::name("balance_log")->insert($arrInsertLog);
    if($resUpdateBalance!==false&&$resInsert)
    {
        return true;
    }else
    {
        return false;
    }
}
function authcode($string, $operation = 'ENCODE', $key = '', $expiry = 0) {
    $ckey_length = 4;
    $key = md5 ( $key ? $key : 'default_key' );
    $keya = md5 ( substr ( $key, 0, 16 ) );
    $keyb = md5 ( substr ( $key, 16, 16 ) );
    $keyc = ($ckey_length ? ($operation == 'DECODE' ? substr ( $string, 0, $ckey_length ) : substr ( md5 ( microtime () ), - $ckey_length )) : '');
    $cryptkey = $keya . md5 ( $keya . $keyc );
    $key_length = strlen ( $cryptkey );
    $string = ($operation == 'DECODE' ? base64_decode ( substr ( $string, $ckey_length ) ) : sprintf ( '%010d', $expiry ? $expiry + time () : 0 ) . substr ( md5 ( $string . $keyb ), 0, 16 ) . $string);
    $string_length = strlen ( $string );
    $result = '';
    $box = range ( 0, 255 );
    $rndkey = array ();

    for($i = 0; $i <= 255; $i ++) {
        $rndkey [$i] = ord ( $cryptkey [$i % $key_length] );
    }

    for($j = $i = 0; $i < 256; $i ++) {
        $j = ($j + $box [$i] + $rndkey [$i]) % 256;
        $tmp = $box [$i];
        $box [$i] = $box [$j];
        $box [$j] = $tmp;
    }

    for($a = $j = $i = 0; $i < $string_length; $i ++) {
        $a = ($a + 1) % 256;
        $j = ($j + $box [$a]) % 256;
        $tmp = $box [$a];
        $box [$a] = $box [$j];
        $box [$j] = $tmp;
        $result .= chr ( ord ( $string [$i] ) ^ $box [($box [$a] + $box [$j]) % 256] );
    }

    if ($operation == 'DECODE') {
        if (((substr ( $result, 0, 10 ) == 0) || (0 < (substr ( $result, 0, 10 ) - time ()))) && (substr ( $result, 10, 16 ) == substr ( md5 ( substr ( $result, 26 ) . $keyb ), 0, 16 ))) {
            return substr ( $result, 26 );
        } else {
            return '';
        }
    } else {
        return $keyc . str_replace ( '=', '', base64_encode ( $result ) );
    }
}
//添加释放订单
function release($uid,$id,$frozen,$balance,$type)
{
    $setting = Db::name('setting')->where('id',11)->find();
    $rel = $balance*$setting['value'];
    $rels = round($rel/3,2);
    $release = Db::name('release')->insert([
        'uid'=>$uid,
        'buy_id'=>$id,
        'number'=>$frozen,
        'release'=>$rel,
        'releases'=>$rels,
        'remaining'=>$frozen,
        'already'=>0,
        'releasetime'=>120,
        'createtime'=>time(),
        'type'=>$type,
        'starttime'=>strtotime(date('Ymd')) + 86400,
        'endtime'=>strtotime(date('Ymd')) +86400*120,
        'principal'=>$balance
    ]);
    if($release)
    {
        return true;
    }else{
        return false;
    }
}
//直推人
function direct($uid)
{
    //获取用户信息
    $user_info = Db::name('user')->where('id',$uid)->find();
    $release = Db::name('release')->where('uid',$uid)->find();
    if(empty($release))
    {
        $res = Db::name('user')->where('id',$user_info['pid'])->setInc('direct',1);
        if ($res)
        {
            return true;
        }else{
            return false;
        }
    }else{
    	return true;
    }
}
//加速奖
//$type
function accelerate($uid,$num,$to='')
{
    Db::startTrans();
    $top = Db::name('setting')->where('id',12)->find();
    $team = Db::name('setting')->where('id',13)->find();
    $ftm = Db::name('setting')->where('id',15)->find();
    $r = array();
    $ft = true;
    //判断是否复投
    $order_count = Db::name('release')->where("uid",$uid)->count();
    if($order_count < 1 ){
        $ft = false;
    }
   //获取用户信息
        $user_info = Db::name('user')->where('id',$uid)->find();
        //获取上一级
        $user_top = Db::name('user')->where('id',$user_info['pid'])->find();
        $order_max = Db::name('release')->where("uid",$user_info['pid'])->where("status",1)->sum("principal");
        if($order_max > $num){
            $num = $order_max;
        }
      	$user_top_money = $num*$top['value'];//上级获得20%
        $user_top_circulate = $user_top_money*0.75;//流通币
        $user_top_circulation = $user_top_money*0.25;//循环币
        //直推流通币红包
        $r[] = add_redpacket($user_info['pid'],1,$user_top_circulate,1);
        //直推循环币红包
        $r[] = add_redpacket($user_info['pid'],2,$user_top_circulation,1);
  	if($to != ''){
    	 //获取用户信息
        $user_info = Db::name('user')->where('id',$to)->find();
    }
   
    

    //$r[] = changeBalance($user_top['id'],'circulate',1,$user_top_circulate,11,"获得直推奖流通币".$user_top_circulate,1);//更改上级流通币
    //$r[] = changeBalance($user_top['id'],'circulation',1,$user_top_circulation,11,"获得直推奖循环币".$user_top_circulation,2);//更改上级循环币
    //团队奖
    $pathArr=array_values(array_filter(explode(",",$user_info["path"])));
    $pathArr=array_reverse($pathArr);
    if(!empty($pathArr)){
        foreach($pathArr as $k=>$v){
            if($k==15)
            {
                break;
            }else{
                $user_info_td = Db::name('user')->where('id',$v)->find();
                if($k < 5 && $user_info_td['direct'] >= 1){
                    $order_max = Db::name('release')->where("uid",$v)->where("status",1)->sum("principal");
                    if($order_max > $num){
                      $num = $order_max;
                    }
                  	if($to == ''){
                        $user_team_money = $num*$team['value'];//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                        $user_ftm_money = $num*$ftm['value'];//复投团队获得1%
                        $user_ftm_circulate = $user_ftm_money*0.75;//流通币
                        $user_ftm_circulation = $user_ftm_money*0.25;//循环币
                        $r[] = add_redpacket($v,1,$user_top_circulate,2);
                        //直推循环币红包
                        $r[] = add_redpacket($v,2,$user_top_circulation,2);
                        //复投奖
                        if($ft){
                            $r[] = add_redpacket($v,1,$user_ftm_circulate,3);
                            $r[] = add_redpacket($v,2,$user_ftm_circulation,3);
                        }
                    }else{
                       	$user_team_money = $num*0.04;//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                      	$r[] = add_redpacket($v,1,$user_top_circulate,4);
                      	$r[] = add_redpacket($v,2,$user_top_circulation,4);
                    }
                }elseif($k >= 5 && $k < 10 && $user_info_td['direct'] >= 5){
                    $order_max = Db::name('release')->where("uid",$v)->where("status",1)->sum("principal");
                    if($order_max > $num){
                         $num = $order_max;
                    }
                  	if($to == ''){
                        $user_team_money = $num*$team['value'];//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                        $user_ftm_money = $num*$ftm['value'];//复投团队获得1%
                        $user_ftm_circulate = $user_ftm_money*0.75;//流通币
                        $user_ftm_circulation = $user_ftm_money*0.25;//循环币
                        $r[] = add_redpacket($v,1,$user_top_circulate,2);
                        //直推循环币红包
                        $r[] = add_redpacket($v,2,$user_top_circulation,2);
                        if($ft){
                            //复投
                            $r[] = add_redpacket($v,1,$user_ftm_circulate,3);
                            $r[] = add_redpacket($v,2,$user_ftm_circulation,3);
                        }
                    }else{
                        $user_team_money = $num*0.04;//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                        $r[] = add_redpacket($v,1,$user_top_circulate,4);
                        $r[] = add_redpacket($v,2,$user_top_circulation,4);
                    }
                }elseif($k >= 10 && $user_info_td['direct'] >= 10){
                    $order_max = Db::name('release')->where("uid",$v)->where("status",1)->sum("principal");
                    if($order_max > $num){
                         $num = $order_max;
                    }
                  	if($to == ''){
                        $user_team_money = $num*$team['value'];//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                        $user_ftm_money = $num*$ftm['value'];//复投团队获得1%
                        $user_ftm_circulate = $user_ftm_money*0.75;//流通币
                        $user_ftm_circulation = $user_ftm_money*0.25;//循环币
                        $r[] = add_redpacket($v,1,$user_top_circulate,2);
                        //直推循环币红包
                        $r[] = add_redpacket($v,2,$user_top_circulation,2);
                        if($ft){
                            //复投
                            $r[] = add_redpacket($v,1,$user_ftm_circulate,3);
                            $r[] = add_redpacket($v,2,$user_ftm_circulation,3);
                        }
                   }else{
                       	$user_team_money = $num*0.04;//团队获得1%
                        $user_top_circulate = $user_team_money*0.75;//流通币
                        $user_top_circulation = $user_team_money*0.25;//循环币
                      	$r[] = add_redpacket($v,1,$user_top_circulate,4);
                      	$r[] = add_redpacket($v,2,$user_top_circulation,4);
                    }
                }

                //$r[] = changeBalance($v,'circulate',1,$user_team_circulate,12,"获得团队奖流通币".$user_top_circulate,1);//更改流通币
                //$r[] = changeBalance($v,'circulation',1,$user_team_circulation,12,"获得团队奖循环币".$user_top_circulation,2);//更改循环币
            }
        }
    } else {
        return true;
    }
    if(!in_array(false,$r))
    {
        Db::commit();
        return true;
    }else{
        Db::rollback();
        return false;
    }
}

function add_redpacket($uid,$type,$num,$genre){
    $arr = array();
    $arr ['uid'] = $uid;
    $arr ['type'] = $type;
    $arr ['num'] = $num;
    $arr ["createtime"] = time();
    $arr ['genre'] = $genre;
    $res = Db::name("red_packet")->insert($arr);
    if($res){
        return true;
    }else{
        return false;
    }
}